package com.bootdo.wx.service.impl;

import com.bootdo.common.utils.*;
import com.bootdo.wx.dao.OrderOrderDao;
import com.bootdo.wx.dao.SetWechatDao;
import com.bootdo.wx.domain.OrderOrderDO;
import com.bootdo.wx.domain.SetWechatDO;
import com.bootdo.wx.service.OrderOrderService;
import com.bootdo.wx.service.WeChatPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class WeChatPayServiceImpl implements WeChatPayService {

	@Autowired
	private OrderOrderService orderOrderService;
	@Autowired
	private SetWechatDao setWechatDao;

	@Override
	public R refund(Map<String,Object> params) {
		try {
			Map <String,String> data = new HashMap<String,String>();
			String  orderId = params.get("orderId").toString();
			OrderOrderDO order = orderOrderService.get(orderId);
			SetWechatDO setWechatDO = setWechatDao.list(new HashMap<String, Object>()).get(0);
			//退款到用户微信
			String nonce_str = MD5Utils.getRandomStringByLength(32);
			//data.put("userId", String.valueOf(userecord.getUserId()));
			data.put("appid", setWechatDO.getAppId());
			data.put("mch_id", setWechatDO.getMchId());
			data.put("nonce_str", nonce_str);
			data.put("sign_type", "MD5");
			data.put("out_trade_no", order.getOrderSn());//商户订单号
			data.put("out_refund_no", order.getId());//商户退款单号,一笔退款失败后重新提交，请不要更换退款单号，请使用原商户退款单号
			int total_fee  = Math.round(Float.valueOf(order.getPayment().multiply(new BigDecimal(100)).toString()));
			data.put("total_fee",String.valueOf(Math.round(total_fee)));//支付金额，微信支付提交的金额是不能带小数点的，且是以分为单位,这边需要转成字符串类型，否则后面的签名会失败
			data.put("refund_fee", String.valueOf(Math.round(total_fee)));//退款总金额,订单总金额,单位为分,只能为整数
			//先支付一分
				/*data.put("total_fee","1");//支付金额，微信支付提交的金额是不能带小数点的，且是以分为单位,这边需要转成字符串类型，否则后面的签名会失败
				data.put("refund_fee", "1");//退款总金额,订单总金额,单位为分,只能为整数*/
	//退款无回调 data.put("notify_url", Constants.NOTIFY_URL_REFUND);//退款成功后的回调地址
			String preStr = PayCommonUtil.createLinkString(data); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
			//MD5运算生成签名，这里是第一次签名，用于调用统一下单接口
			String mySign = PayCommonUtil.sign(preStr, setWechatDO.getKey(), "utf-8").toUpperCase();
			data.put("sign", mySign);

			//拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去
			String xmlStr = WeChatPayUtils.postData("https://api.mch.weixin.qq.com/secapi/pay/refund", PayCommonUtil.GetMapToXML(data), setWechatDO); //支付结果通知的xml格式数据
			System.out.println(xmlStr);
			Map notifyMap = PayCommonUtil.doXMLParse(xmlStr);
			if ("SUCCESS".equals(notifyMap.get("return_code"))) {
				if("SUCCESS".equals(notifyMap.get("result_code"))) {
					//退款成功的操作
					OrderOrderDO orderOrderDO = new OrderOrderDO();
					orderOrderDO.setId(orderId);
					orderOrderDO.setStatus(6);
					orderOrderService.backOrder(orderOrderDO);
					return R.ok("退款成功");
				}else{
					System.out.println("退款失败:原因"+notifyMap.get("err_code_des"));
					return R.error(1,(String)notifyMap.get("err_code_des"));
				}
			}else{
				System.out.println("退款失败:原因"+notifyMap.get("return_msg"));
				return R.error(2,(String)notifyMap.get("return_msg"));
			}
		}catch (Exception e) {
			return R.error("系统错误");
		}


	}

	
}
